<template>
  <div class="search-hot">
    <!-- 搜索 "结果" 组件 -->
    <h3>最佳匹配</h3>
    <search-singer :keywords="keywords"></search-singer>
    <music-list
      :musiclist="searchResult"
      :keyword="keywords"
      :currentmusic="currentmusic"
      @play="$emit('play', $event)"
    ></music-list>
    <!-- 加载更多 -->
    <load-animate v-show="isloading"></load-animate>
    <div class="loadmore" @click.stop="loadMore" ref="loadmore">
      加载更多...
    </div>
  </div>
</template>

<script>
// 计算属性一般用在同步代码
// 侦听器异步代码
import MusicList from "./MusicList.vue";
import SearchSinger from "./SearchSinger.vue";
import _ from "lodash";
import LoadAnimate from "./LoadAnimate.vue";
//接口：  /cloudsearch?keywords=海阔天空
//多重匹配接口： /search/multimatch?keywords=海阔天空
export default {
  components: { MusicList, SearchSinger, LoadAnimate },
  props: {
    keywords: {
      type: String,
      default: "",
    },
    currentmusic: {
      type: Object,
      default: () => {
        return null;
      },
    },
  },
  data() {
    return {
      searchResult: [],
      page: 1,
      isloading: true, //显示loading
      album: null, //专辑
    };
  },
  created() {
    this.getSearchResult();
    this.getAlbum();
    this.setHistory();
  },
  mounted() {
    window.addEventListener("scroll", this.scrollEvent);
  },
  beforeDestroy() {
    window.removeEventListener("scroll", this.scrollEvent);
  },
  methods: {
    scrollEvent: _.debounce(function () {
      let scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop; //获取卷去的高度
      let loadmoreTop = this.$refs.loadmore.offsetTop; //获取loadmore距离顶部的距离
      let windowHeight = window.innerHeight; //获取窗口高度
      if (scrollTop + windowHeight >= loadmoreTop - 50) {
        //触底
        this.loadMore();
      }
    }, 300),
    async getAlbum() {
      await this.axios
        .get(`/cloudsearch?keywords=${this.keywords}&type=100`)
        .then((re) => {
          console.log("歌手==>", re.result.artists[0].id);
        });
    },
    // 歌手 type = 100   歌单 type = 1000
    async getSearchResult(offset = 0) {
      await this.axios
        .get(
          `/cloudsearch?keywords=${this.keywords}&type=1&limit=20&offset=${offset}`
        )
        .then((re) => {
          let searchResult = re.result.songs.map((item) => {
            item.song = {
              album: item.al,
              alias: item.alia,
              artists: item.ar,
              privilege: item.privilege,
            };
            return item;
          });
          this.searchResult = this.searchResult.concat(searchResult); //把每次搜索的结果合并到数组
          this.isloading = false;
          // console.log("------------", this.searchResult);
        });
    },
    // (`/cloudsearch?keywords=${this.keywords}&type=1&limit=20&offset=0`)  第1页 取20条 跳过0条   20*(page-1) = 0
    // (`/cloudsearch?keywords=${this.keywords}&type=1&limit=20&offset=20`) 第2页 取20条 跳过20条                20
    // (`/cloudsearch?keywords=${this.keywords}&type=1&limit=20&offset=40`) 第3页 取20条 跳过40条                40
    // (`/cloudsearch?keywords=${this.keywords}&type=1&limit=20&offset=60`) 第4页 取20条 跳过60条                60

    loadMore() {
      this.isloading = true;
      this.page++;
      let offset = 20 * (this.page - 1);
      this.getSearchResult(offset);
    },

    setHistory() {
      if (!this.keywords || this.keywords == "" || this.keywords.length < 1) {
        return;
      }
      // 先取出history里面的结果
      let historys = localStorage.getItem("searchhistory");
      let historyArr = [];
      if (historys) {
        historyArr = JSON.parse(historys); //还原localStorage数据
      }
      historyArr.unshift(this.keywords); // 把最新的搜索关键词存储到localStorage数据中
      // let setArr = new Set(historyArr);//ES6 去重、数组作为参数
      // historyArr = [...setArr]; // 还原成数组
      // console.log(setArr);

      // 用lodash去重
      historyArr = _.uniq(historyArr);
      localStorage.setItem("searchhistory", JSON.stringify(historyArr));
    },
  },
};
</script>

<style lang="scss" scoped>
.search-hot {
  .loadmore {
    font-size: 12px;
    line-height: 50px;
    text-align: center;
    cursor: pointer;
  }
  h3 {
    margin-left: 10px;
    font-size: 12px;
    line-height: 16px;
    color: #666;
  }
}
</style>